<template>
  <div class="pluto-table-print">
    <el-card>
      <div slot="header" v-if="title.length>0" class="card-header">
        <span>{{ title }}</span>
      </div>

      <!-- 筛选区域 -->
      <div class="filter-section">
        <el-input
          v-model="tempFilterText"
          :placeholder="filterPlaceholder"
          clearable
          style="width: 300px; margin-right: 10px;"
          @keyup.enter="handleFilter"
          @blur="handleBlur"
        >
          <i slot="prefix" class="el-input__icon el-icon-search"></i>
        </el-input>
        <el-button
          type="primary"
          icon="el-icon-search"
          @click="handleFilter"
          :loading="filterLoading"
        >
          筛选
        </el-button>
<!--        <el-button-->
<!--          v-if="filterText"-->
<!--          @click="handleResetFilter"-->
<!--        >-->
<!--          重置-->
<!--        </el-button>-->
      </div>

      <!-- 表格区域 -->
      <div class="table-section">
        <el-table
          ref="tableRef"
          :data="tableData"
          style="width: 100%"
          @selection-change="handleSelectionChange"
          border
          stripe
          v-loading="loading"
        >
          <!-- 多选框列 -->
          <el-table-column
            v-if="showSelection"
            type="selection"
            width="50"
            align="center"
          ></el-table-column>

          <!-- 循环生成所有列 -->
          <template v-for="column in columns">
            <!-- 自定义渲染列（使用插槽） -->
            <el-table-column
              v-if="column.slot"
              :key="column.prop"
              :prop="column.prop"
              :label="column.label"
              :width="column.width"
              :min-width="column.minWidth"
              :sortable="column.sortable"
              :align="column.align || 'left'"
            >
              <template slot-scope="scope">
                <slot :name="column.slot" :row="scope.row" :index="scope.$index"></slot>
              </template>
            </el-table-column>

            <!-- 自动渲染列（直接显示文本） -->
            <el-table-column
              v-else
              :key="column.prop"
              :prop="column.prop"
              :label="column.label"
              :width="column.width"
              :min-width="column.minWidth"
              :sortable="column.sortable"
              :align="column.align || 'left'"
            ></el-table-column>
          </template>
        </el-table>
      </div>

      <!-- 分页区域 -->
      <div class="pagination-section" v-if="showPagination">
<!--        <div class="selected-info" v-if="showSelection">-->
<!--          已选择 {{ selectedRows.length }} 条记录-->
<!--        </div>-->
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="pageSizes"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">  <!-- 直接使用传入的 total -->
        </el-pagination>
      </div>

      <!-- 操作按钮区域 -->
<!--      <div class="action-section" v-if="showActions">-->
<!--        <el-button @click="handleCancel">{{ cancelText }}</el-button>-->
<!--        <el-button type="primary" @click="handlePrint">{{ printText }}</el-button>-->
<!--      </div>-->
    </el-card>
  </div>
</template>

<script>
export default {
  name: 'PlutoTablePrint',
  props: {
    title: {
      type: String,
      default: ''
    },
    columns: {
      type: Array,
      required: true,
      default: () => []
    },
    tableData: {
      type: Array,
      required: true,
      default: () => []
    },
    showSelection: {
      type: Boolean,
      default: true
    },
    showIndex: {
      type: Boolean,
      default: false
    },
    showPagination: {
      type: Boolean,
      default: true
    },
    showActions: {
      type: Boolean,
      default: true
    },
    filterPlaceholder: {
      type: String,
      default: '输入关键字进行筛选'
    },
    // 新增：是否在失去焦点时自动触发筛选
    filterOnBlur: {
      type: Boolean,
      default: true
    },
    cancelText: {
      type: String,
      default: '取消'
    },
    printText: {
      type: String,
      default: '确认打印'
    },
    pageSizes: {
      type: Array,
      default: () => [5, 10, 20, 50]
    },
    defaultPageSize: {
      type: Number,
      default: 5
    },
    total: {
      type: Number,
      default: 0
    },
    loading: {
      type: Boolean,
      default: false
    },
    filterFields: {
      type: Array,
      default: null
    },
    // 新增：是否启用实时筛选
    realtimeFilter: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      // 临时筛选文本（输入框的值）
      tempFilterText: '',
      // 实际筛选文本（用于筛选）
      filterText: '',
      currentPage: 1,
      pageSize: this.defaultPageSize,
      selectedRows: [],
      // 筛选按钮加载状态
      filterLoading: false
    }
  },
  watch: {
    tableData: {
      handler() {
        this.selectedRows = [];
        if (this.$refs.tableRef) {
          this.$refs.tableRef.clearSelection();
        }
      },
      deep: true
    },
    defaultPageSize(newVal) {
      this.pageSize = newVal;
    },
    // 如果启用实时筛选，监听输入框变化
    tempFilterText(newVal) {
      if (this.realtimeFilter) {
        // 防抖处理，避免频繁触发
        clearTimeout(this.filterTimer);
        this.filterTimer = setTimeout(() => {
          this.filterText = newVal;
          this.currentPage = 1;
        }, 300);
      }
    }
  },
  methods: {
    // 外部调用方法：获取选中数据
    getSelectedData() {
      return this.selectedRows;
    },
    // 失去焦点处理
    handleBlur() {
      // 如果启用了失去焦点筛选，则触发筛选
      if (this.filterOnBlur) {
        // 去除前后空格
        this.tempFilterText = this.tempFilterText.trim();

        // 只有当内容发生变化时才触发筛选
        if (this.tempFilterText !== this.filterText) {
          this.handleFilter();
        }
      }
    },
    // 筛选处理
    handleFilter() {
      // 设置筛选按钮加载状态
      this.filterLoading = true;

      // 模拟筛选操作，实际应用中可能是异步操作
      setTimeout(() => {
        this.filterText = this.tempFilterText;
        this.currentPage = 1; // 筛选后回到第一页
        this.filterLoading = false;

        // 触发筛选事件
        this.$emit('filter', this.filterText);
      }, 300);
    },

    // 重置筛选
    handleResetFilter() {
      this.tempFilterText = '';
      this.filterText = '';
      this.currentPage = 1;
      this.$emit('filter-reset');
    },

    handleSelectionChange(selection) {
      this.selectedRows = selection;
      this.$emit('selection-change', selection);
    },

    handleSizeChange(val) {
      this.pageSize = val;
      this.currentPage = 1;
      this.$emit('size-change', val);
    },

    handleCurrentChange(val) {
      this.currentPage = val;
      this.$emit('current-change', val);
    },

    handleCancel() {
      this.$confirm('确定要取消操作吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        this.selectedRows = [];
        if (this.$refs.tableRef) {
          this.$refs.tableRef.clearSelection();
        }
        this.$emit('cancel');
        this.$message({
          type: 'info',
          message: '已取消',
        });
      }).catch(() => {
        // 用户点击取消
      });
    },

    handlePrint() {
      if (this.showSelection && this.selectedRows.length === 0) {
        this.$message.warning('请至少选择一条记录');
        return;
      }

      this.$confirm(
        this.showSelection
          ? `确定要打印选中的 ${this.selectedRows.length} 条记录吗？`
          : '确定要打印当前数据吗？',
        '确认打印',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'success',
        }
      ).then(() => {
        const printData = this.showSelection ? this.selectedRows : this.tableData;
        this.$emit('print', printData);

        this.$message.success(
          this.showSelection
            ? `成功打印 ${this.selectedRows.length} 条记录`
            : '打印成功'
        );

        if (this.showSelection) {
          this.selectedRows = [];
          if (this.$refs.tableRef) {
            this.$refs.tableRef.clearSelection();
          }
        }
      }).catch(() => {
        // 用户点击取消
      });
    },

    // 外部调用方法：设置筛选条件
    setFilter(filterValue) {
      this.tempFilterText = filterValue;
      this.filterText = filterValue;
      this.currentPage = 1;
    },

    // 外部调用方法：清空筛选
    clearFilter() {
      this.handleResetFilter();
    }
  },
  mounted() {
    this.pageSize = this.defaultPageSize;
  }
}
</script>

<style scoped>
.pluto-table-print {
  margin: 20px auto;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.filter-section {
  margin-bottom: 20px;
  display: flex;
  align-items: center;
}

.table-section {
  margin-bottom: 20px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  overflow: hidden;
}

.pagination-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.action-section {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.selected-info {
  color: #606266;
  font-size: 14px;
}

.card-header {
  font-size: 18px;
  font-weight: bold;
}
</style>
